package com.zitangkou.user.handler;

import com.zitangkou.common.enums.RespEnum;
import com.zitangkou.common.global.GlobalException;
import com.zitangkou.common.global.GlobalResp;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.converter.HttpMessageConversionException;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * @author Deng Ningning
 * @version 1.0
 * @date 2020/8/14 17:32
 */
@Slf4j
@ControllerAdvice
public class GlobalExceptionHandler {
    @ResponseBody
    @ExceptionHandler(value = Exception.class)
    public GlobalResp<String> handle(Exception e) {
        // 自定义异常返回
        if (e instanceof GlobalException) {
            GlobalException hException = (GlobalException) e;
            log.info(hException.getMsg());
            return GlobalResp.success(hException);
        }
        // 参数异常
        if (e instanceof HttpMessageConversionException) {
            log.info(e.getClass() + " " + e.getMessage());
            return GlobalResp.success(
                    new GlobalException(RespEnum.PARAM_ERROR)
            );
        }
        // 参数校验异常
        if (e instanceof MethodArgumentNotValidException) {
            log.info(e.getClass() + " " + e.getMessage());
            BindingResult result = ((MethodArgumentNotValidException) e).getBindingResult();
            GlobalException globalException;
            // 自定义错误提示
            if (result.hasErrors()) {
                globalException = new GlobalException(
                        RespEnum.PARAM_ERROR.getCode(),
                        result.getFieldErrors().get(0).getDefaultMessage());
            } else {
                globalException = new GlobalException(RespEnum.PARAM_ERROR);
            }
            return GlobalResp.success(globalException);
        }
        // 其它
        log.info(e.getClass() + " " + e.getMessage());
        return GlobalResp.success(
                new GlobalException(RespEnum.EXCEPTION.getCode()
                        , "系统异常！【" + e.getMessage() + "】")
        );
    }
}
